<!-- 开支编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="640"
    :model-value="modelValue"
    :title="form.id > 0 ? '修改回款' : '新建回款'"
    @update:modelValue="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="企业" prop="company">
        <el-input
          clearable
          v-model="form.company"
          placeholder="请选择"
          style="width: 300px"
          readonly
        />
      </el-form-item>

      <!-- 快捷月份选择 -->
      <el-form-item label="所属月份" prop="belongs_date">
        <el-date-picker
          v-model="form.belongs_date"
          type="month"
          placeholder="选择月份"
          style="width: 150px"
          value-format="YYYY-MM"
        />
      </el-form-item>
      <el-form-item label="回款日期" prop="paid_date">
        <el-date-picker
          v-model="form.paid_date"
          type="date"
          placeholder="选择回款日期"
          style="width: 150px"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="关联发票" prop="invoice_ids">
        <el-select
          multiple
          v-model="form.invoice_ids"
          placeholder="请选择"
          style="width: 300px"
        >
          <el-option
            v-for="item in invoiceList"
            :key="item.id"
            :label="item.amount + '元 - ' + item.invoice_date"
            :value="String(item.id)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="金额" prop="amount">
        <el-input
          v-model="form.amount"
          style="width: 150px"
          @input="handleInput"
        />
      </el-form-item>

      <el-form-item label="备注">
        <el-input clearable v-model="form.remark" style="width: 400px" />
      </el-form-item>
      <el-form-item label="凭证">
        <image-upload :limit="1000" v-model="form.images" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { useFormData } from '@/utils/use-form-data';
  import {
    updateCompanyPaid,
    pageCompanyInvoice,
    getCompanyById
  } from '@/api/company';
  import ImageUpload from '@/components/ImageUpload/index.vue';
  const emit = defineEmits(['done', 'update:modelValue']);

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object,
    companyId: Number
  });

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 表单数据 */
  const [form, resetFields, assignFields] = useFormData({
    id: 0,
    tenant_id: '',
    company_id: '',
    company: '',
    amount: '',
    images: '',
    remark: '',
    belongs_date: ''
  });

  const company = ref([]);

  /** 表单验证规则 */
  const rules = reactive({
    company: [
      {
        required: true,
        message: '请选择项目',
        type: 'string',
        trigger: 'blur'
      }
    ],

    belongs_date: [
      {
        required: true,
        message: '请选择所属月份',
        type: 'string',
        trigger: 'blur'
      }
    ],

    amount: [
      {
        required: true,
        message: '请填写金额',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  const handleInput = () => {
    let value = form.amount;

    // 只允许输入数字、小数点和负号
    value = value.replace(/[^\d.-]/g, '');

    // 负号只能出现在最前面
    value = value.replace(/^-+/, '-').replace(/(.)-/g, '$1');

    // 确保只出现一个小数点
    value = value.replace(/(\..*)\./g, '$1');

    // 处理前导零，避免 0001 这种情况，允许 0.x 和 -0.x
    value = value.replace(/^-?0+(\d)/, '-$1');

    form.amount = value;
  };

  /** 保存编辑 */
  const save = () => {
    console.log(form);
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      loading.value = true;

      updateCompanyPaid(form)
        .then((msg) => {
          loading.value = false;
          EleMessage.success(msg);
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          EleMessage.error(e.message);
        });
    });
  };
  /** 发票 */
  const invoiceList = ref([]);
  const getInvoice = () => {
    pageCompanyInvoice({
      status: 200,
      company_id: form.company_id,
      belongs_date: form.belongs_date,
      page: 1,
      limit: 99999999
    })
      .then((res) => {
        invoiceList.value = res.list;
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const getCompany = () => {
    getCompanyById({ id: props.companyId })
      .then((res) => {
        const e = res;
        company.value = e;
        form.company = e.company_name;
        form.company_id = e.id;
        form.tenant_id = e.tenant_id;
        form.site_id = e.site_id;
      })
      .catch((e) => {
        loading.value = false;
        EleMessage.error(e.message);
      });
  };

  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        if (props.data) {
          assignFields({
            ...props.data
          });
        }
        getCompany();
      } else {
        resetFields();
        invoiceList.value = [];
        resetTriggered();
        formRef.value?.clearValidate?.();
      }
    }
  );
  const triggered = reactive({
    company: false,
    date: false
  });

  watch(
    () => form.company_id,
    (val) => {
      if (val !== '') {
        triggered.company = true;
        checkAndGetInvoice();
      }
    }
  );

  watch(
    () => form.belongs_date,
    (val) => {
      if (val !== '') {
        triggered.date = true;
        checkAndGetInvoice();
      }
    }
  );

  const resetTriggered = () => {
    triggered.company = false;
    triggered.date = false;
  };

  const checkAndGetInvoice = () => {
    if (triggered.company && triggered.date) {
      getInvoice();
    }
  };
</script>
